package com.my.helper.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.my.helper.R;
import com.my.helper.util.CacheActivity;
import com.my.helper.util.MyDataBaseHelper;
import com.my.helper.util.SharedPrefUtil;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 重写WebChromeClient#onProgressChanged方法
 * 当newProgress==100的时候,开启属性动画让水平进度条渐变消失
 * 当newProgress<100的时候,开启属性动画让进度平滑递增
 */
public class MessageWebViewActivity extends AppCompatActivity implements View.OnClickListener {
    /**
     * 返回按钮
     */
    private RelativeLayout rlBack;
    /**
     * WebView
     */
    private WebView webViewMy;
    /*** 传递过来的url */
    private String url;
    // 标题
    private TextView tvTitle;
    private String strTitle;
    private ProgressBar mProgressBar;
    private boolean isAnimStart = false;
    private int currentProgress;
    private String type;
    private MyDataBaseHelper mSql;
    private SharedPrefUtil sp;
    private int userId;
    private String time;
    private String strNewsTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_web_view);
        CacheActivity.addActivity(this);
        sp = new SharedPrefUtil(this, "myHelper");
        initViews();
    }

    private void initViews() {
        tvTitle = findViewById(R.id.tv_title_message_web);
        rlBack = findViewById(R.id.rl_back_message_web);
        rlBack.setOnClickListener(this);
        webViewMy = findViewById(R.id.wv_message_web);
        mProgressBar = findViewById(R.id.progressBar);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        time = simpleDateFormat.format(date);

        Intent dataIntent = getIntent();
        strTitle = dataIntent.getStringExtra("web_message_title");
        url = dataIntent.getStringExtra("web_message_url");
        type = dataIntent.getStringExtra("web_message_type");
        userId = Integer.valueOf(sp.getString("user_id", "0"));
        strNewsTitle = getIntent().getStringExtra("web_message_news_title");
        mSql = new MyDataBaseHelper(this, "Helper.db", null, 1);

        if (type.equals("历史")) {

        } else {
            SQLiteDatabase db = mSql.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("uid", userId);
            values.put("url", url);
            values.put("type", type);
            values.put("time", time);
            values.put("title", strNewsTitle);
            db.insert("MyHistory", null, values);
            values.clear();
            db.close();
        }

        if (strTitle != null) {
            tvTitle.setText(strTitle);
        }

        webViewMy.setWebViewClient(new WebViewClient());
        webViewMy.getSettings().setJavaScriptEnabled(true);// 启用JS
        webViewMy.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                lodurl(view, url);
                return false;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                mProgressBar.setVisibility(View.VISIBLE);
                mProgressBar.setAlpha(1.0f);
            }
        });

        // 获取网页加载进度
        webViewMy.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                currentProgress = mProgressBar.getProgress();
                if (newProgress >= 100 && !isAnimStart) {
                    // 防止调用多次动画
                    isAnimStart = true;
                    mProgressBar.setProgress(newProgress);
                    // 开启属性动画让进度条平滑消失
                    startDismissAnimation(mProgressBar.getProgress());
                } else {
                    // 开启属性动画让进度条平滑递增
                    startProgressAnimation(newProgress);
                }
            }
        });

        WebSettings webSettings = webViewMy.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webViewMy.loadUrl(url);
    }

    /**
     * progressBar递增动画
     */
    private void startProgressAnimation(int newProgress) {
        ObjectAnimator animator = ObjectAnimator.ofInt(mProgressBar, "progress", currentProgress, newProgress);
        animator.setDuration(300);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.start();
    }


    /**
     * progressBar消失动画
     */
    private void startDismissAnimation(final int progress) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(mProgressBar, "alpha", 1.0f, 0.0f);
        anim.setDuration(1500);  // 动画时长
        anim.setInterpolator(new DecelerateInterpolator());     // 减速
        // 关键, 添加动画进度监听器
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float fraction = valueAnimator.getAnimatedFraction();      // 0.0f ~ 1.0f
                int offset = 100 - progress;
                mProgressBar.setProgress((int) (progress + offset * fraction));
            }
        });

        anim.addListener(new AnimatorListenerAdapter() {

            @Override
            public void onAnimationEnd(Animator animation) {
                // 动画结束
                mProgressBar.setProgress(0);
                mProgressBar.setVisibility(View.GONE);
                isAnimStart = false;
            }
        });
        anim.start();
    }

    public void lodurl(final WebView webView, final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_back_message_web:
                CacheActivity.finishSingleActivityByClass(MessageWebViewActivity.class);
                break;
        }
    }
}
